package Aleehot100;

import java.util.*;

/**
 * ClassName: c075
 * Package: Aleehot100
 * Description: 347. 前 K 个高频元素
 *
 * @Author BCXJ
 * @Create 2025/8/28 21:50
 * @Version 1.0
 * @Since 1.0
 */
public class c075 {
    public static void main(String[] args) {
        int[] arr = {4,1,2,1};
        System.out.println(Arrays.toString(topKFrequent(arr, 1)));
    }

    // 小跟堆实现
    // n*log(k) -> k是数组不重复的元素
    public static int[] topKFrequent(int[] nums, int k) {
        if(null == nums) {
            return null;
        }
        // 1 统计每个数出现的频率
        Map<Integer, Integer> mapIndex = new HashMap<>();
        for (int num : nums) {
            mapIndex.put(num, mapIndex.getOrDefault(num, 0) + 1);
        }
        // 2 基于频率建立小跟堆
        PriorityQueue<int[]> minHeap = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]);
        Set<Map.Entry<Integer, Integer>> entries = mapIndex.entrySet();
        for (Map.Entry<Integer, Integer> entry : entries) {
            Integer key = entry.getKey();
            Integer value = entry.getValue();
            minHeap.add(new int[]{key, value});
            if(minHeap.size() > k) {
                minHeap.poll();
            }
        }
        // 3 返回前k个元素
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = Objects.requireNonNull(minHeap.poll())[0];
        }
        return res;
    }
}
